package com.demo03.test01;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class ThreadLocalScopeShareData {
    //private static int data = 0;
    //private static Map<Thread, Integer> shareData = new HashMap<>();
    private static ThreadLocal<Integer> x = new ThreadLocal<>();
    private static ThreadLocal<Person> p = new ThreadLocal<>();

    public static void main(String[] args) {

        //ExecutorService executor = Executors.newFixedThreadPool(2);

        for (int i = 0; i < 2; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int data = new Random().nextInt(100);
                    System.out.println(Thread.currentThread().getName() + " : " + data);
                    x.set(data);
                    Person person = new Person();
                    person.setName("name : " + data);
                    person.setAge(data);
                    p.set(person);
                    new A().get();
                    new B().get();
                }
            }).start();
        }
    }

    static class A {
        public void get() {
            int data = x.get();
            System.out.println(" A: " + Thread.currentThread().getName() + " : " + data);
            Person person = p.get();
            System.out.println(" A: " + Thread.currentThread().getName() + " : " + "Person{" +
                    "name='" + person.getName() + '\'' +
                    ", age=" + person.getAge() +
                    '}');

        }
    }

    static class B {
        public void get() {
            int data = x.get();
            System.out.println(" B: " + Thread.currentThread().getName() + " : " + data);
            Person person = p.get();
            System.out.println(" B: " + Thread.currentThread().getName() + " : " + "Person{" +
                    "name='" + person.getName() + '\'' +
                    ", age=" + person.getAge() +
                    '}');
        }
    }
}

class Person {
    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
